package com.gexiaobao.pigeon.ui.organizer.fragment

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.inputmethod.EditorInfo
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.hideSoftKeyboard
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.ext.initFooter
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.ext.showEmpty
import com.gexiaobao.pigeon.app.ext.showLoading
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.TransInformation
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentPigeonListInfoBinding
import com.gexiaobao.pigeon.ui.adapter.PigeonListAdapter
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.viewmodel.MyPigeonViewModel
import com.gexiaobao.pigeon.viewmodel.request.RequestPigeonListViewModel
import com.kingja.loadsir.core.LoadService
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat

/**
 * @Author      : hxw
 * @Date        : 2023/6/1 12:23
 * @Describe    : 会员下的赛鸽列表
 */
class FragmentPigeonListInfo : BaseFragment<MyPigeonViewModel, FragmentPigeonListInfoBinding>() {

    private val mAdapter: PigeonListAdapter by lazy { PigeonListAdapter(arrayListOf()) }
    private lateinit var dialog: RxDialogDefault

    //界面状态管理者
    private lateinit var loadsir: LoadService<Any>
    private var userId: Int = 0
    private var entryName = ""

    //请求数据ViewModel
    private val pigeonViewModel: RequestPigeonListViewModel by viewModels()

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewmodel = mViewModel
        userId = requireArguments().getInt("userId")
        entryName = arguments?.getString("entryName").toString()
        val title = arguments?.getString("title")
        title?.let {
            mDatabind.toolbar.initClose(it) {
                nav().navigateUp()
            }
        }
        mDatabind.etSearch.transformationMethod = TransInformation()//小写自动转大写
        mDatabind.etSearch.setOnEditorActionListener { _, i, _ ->
            when (i) {
                EditorInfo.IME_ACTION_SEARCH ->
                    searchPigeon()

                else -> {}
            }
            false
        }

        mDatabind.layoutList.swipeRecyclerView.init(LinearLayoutManager(context), mAdapter).let {
            it.addItemDecoration(SpaceItemDecoration(0, Util.dp2px(context, 1f)))
            it.initFooter {
                //触发加载更多时请求数据
                pigeonViewModel.getPigeonList(false, "1", mViewModel.searchName.get(), userId)
            }
        }

        //状态页配置
        loadsir = loadServiceInit(mDatabind.layoutList.swipeRefreshLayout) {
            //点击重试时触发的操作
            loadsir.showLoading()
            pigeonViewModel.getPigeonList(true, "1", mViewModel.searchName.get(), userId)
        }

        mDatabind.layoutList.swipeRefreshLayout.init {
            loadsir.showLoading()
            pigeonViewModel.getPigeonList(true, "1", mViewModel.searchName.get(), userId)
        }

        mAdapter.addChildClickViewIds(R.id.tv_item_pigeon_delete)
        mAdapter.addChildClickViewIds(R.id.tv_item_pigeon_modify)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.tv_item_pigeon_delete -> {
                    deletePigeon(position)
                }

                R.id.tv_item_pigeon_modify -> {
                    nav().navigateAction(R.id.action_pigeon_list_to_add_pigeon, Bundle().apply {
                        putInt("userId", userId)
                        putInt("type", 1)//type = 1：修改
                        putSerializable("data", mAdapter.data[position])
                    })
                }
            }
        }

        mDatabind.etSearch.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable?) {
                if (s?.isEmpty() == true) {
                    loadsir.showLoading()
                    pigeonViewModel.getPigeonList(true, "1", mViewModel.searchName.get(), userId)
                }
            }
        })
    }

    private fun deletePigeon(position: Int) {
        dialog = RxDialogDefault(context)
        dialog.setTitle("是否删除此赛鸽")
        dialog.setSureListener {
            dialog.dismiss()
            showLoading(getString(R.string.loading))
            pigeonViewModel.orgDeletePigeon(mAdapter.data[position].pigeonId.toString())
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun searchPigeon() {
        hideSoftKeyboard(activity)
        when {
            mViewModel.searchName.get().isEmpty() -> showMessage("请输入要查询的足环号")
            else -> {
                loadsir.showLoading()
                pigeonViewModel.getPigeonList(true, "1", mViewModel.searchName.get(), userId)
            }
        }
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        loadsir.showLoading()
        pigeonViewModel.getPigeonList(true, "1", mViewModel.searchName.get(), userId)
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.tvSearch, mDatabind.tvPigeonListAdd) {
            when (it) {
                mDatabind.tvSearch -> {
                    searchPigeon()
                }

                mDatabind.tvPigeonListAdd -> {
                    nav().navigateAction(R.id.action_pigeon_list_to_add_pigeon, Bundle().apply {
                        putInt("userId", userId)
                        putInt("type", 2)//type = 2：添加
                        putString("entryName", entryName)
                    })
                }
            }
        }
    }

    override fun createObserver() {
        super.createObserver()
        pigeonViewModel.pigeonData.observe(viewLifecycleOwner) {
            loadListData(it, mAdapter, loadsir, mDatabind.layoutList.swipeRecyclerView, mDatabind.layoutList.swipeRefreshLayout)
        }

        pigeonViewModel.orgDeletePigeonResult.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                dismissLoading()
                dialog.dismiss()
                loadsir.showLoading()
                pigeonViewModel.getPigeonList(true, "1", mViewModel.searchName.get(), userId)
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
    }
}